<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能考试系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 900px;
            margin: 30px auto;
            padding: 20px;
            background: white;
            border-radius: 10px;
            box-shadow:  0 5px 15px rgba(0, 0, 0, 0.1);
            position: relative;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
            position: relative; /* 为退出按钮定位 */
        }
		#video {
		    width: 100%;
		    height: 100%;
		    object-fit: cover;
		}
		
		.camera-container {
		    position: fixed;
		    top: 20px;
		    left: 20px;
		    width: 160px;
		    height: 120px;
		    z-index: 1000;
		    border: 2px solid #3498db;
		    border-radius: 5px;
		    overflow: hidden;
		    background: #000;
		    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
		}
        .header h1 {
            color: #2c3e50;
            margin-bottom: 10px;
        }
        
        /* 新增：退出考试按钮样式 */
        .exit-exam-btn {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 8px 16px;
            background-color: #f39c12;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .exit-exam-btn:hover {
            background-color: #e67e22;
        }
        
        .progress-bar {
            height: 10px;
            background: #ecf0f1;
            border-radius: 5px;
            margin: 15px 0;
            overflow: hidden;
        }
        
        .progress {
            height: 100%;
            background: #3498db;
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .question-container {
            margin-bottom: 25px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #3498db;
        }
        
        .question-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        
        .question-number {
            background: #3498db;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 14px;
        }
        
        .question-content {
            font-size: 16px;
            line-height: 1.7;
        }
        
        .answer-container {
            margin-bottom: 20px;
        }
        
        .answer-container h3 {
            margin-bottom: 10px;
            color: #2c3e50;
        }
        
        textarea {
            width: 100%;
            height: 150px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            resize: vertical;
            font-size: 15px;
        }
        
        textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }
        
        .btn-container {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
            flex: 1;
        }
        
        .btn-primary:hover {
            background: #2980b9;
        }
        
        .btn-secondary {
            background: #ecf0f1;
            color: #7f8c8d;
        }
        
        .btn-secondary:hover {
            background: #d5dbdb;
        }
        
        .btn-warning {
            background: #f39c12;
            color: white;
        }
        
        .btn-warning:hover {
            background: #d35400;
        }
        
        .result-container {
            margin-top: 30px;
            padding: 20px;
            background: #e8f4fc;
            border-radius: 8px;
            display: none;
            position: relative;
            padding-bottom: 70px;
        }
        
        .result-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        
        .score {
            font-size: 24px;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .feedback {
            background: white;
            padding: 15px;
            border-radius: 5px;
            margin-top: 15px;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            display: none;
        }
        
        .spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border-left-color: #3498db;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        
        .total-score-container {
            background: #e8f4fc;
            border-radius: 8px;
            padding: 20px;
            margin-top: 20px;
            display: none;
        }
        
        .total-score-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 15px;
        }
        
        .total-score {
            font-size: 28px;
            font-weight: bold;
            color: #27ae60;
        }
        
        .question-scores {
            margin-top: 15px;
            background: white;
            padding: 15px;
            border-radius: 5px;
        }
        
        .score-item {
            display: flex;
            justify-content: space-between;
            padding: 5px 0;
            border-bottom: 1px solid #eee;
        }
        
        .score-item:last-child {
            border-bottom: none;
        }
        
        .next-btn-container {
            position: absolute;
            bottom: 15px;
            right: 15px;
        }
        
        .next-btn {
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 15px;
            font-weight: 500;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 8px;
            background: #27ae60;
            color: white;
        }
        
        .next-btn:hover {
            background: #219653;
        }

        /* 新增语音输入相关样式 */
        .voice-input-container {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .voice-btn {
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            border: none;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .voice-btn-start {
            background: #2ecc71;
            color: white;
        }
        
        .voice-btn-stop {
            background: #e74c3c;
            color: white;
        }
        
        .voice-btn-start:hover {
            background: #27ae60;
        }
        
        .voice-btn-stop:hover {
            background: #c0392b;
        }
        
        .voice-status {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #7f8c8d;
            font-size: 14px;
        }
        
        .recording-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #e74c3c;
            animation: pulse 1.5s infinite;
            display: none;
        }
        
        @keyframes pulse {
            0% { transform: scale(0.95); opacity: 0.7; }
            50% { transform: scale(1.1); opacity: 1; }
            100% { transform: scale(0.95); opacity: 0.7; }
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        @media (max-width: 768px) {
            .container {
                margin: 15px;
                padding: 15px;
            }
			.camera-container {
            width: 120px;
            height: 90px;
            top: 10px;
            left: 10px;
        }
            .btn-container {
                flex-direction: column;
            }
            
            .next-btn-container {
                position: static;
                margin-top: 20px;
                text-align: right;
            }
            
            /* 响应式调整退出按钮位置 */
            .exit-exam-btn {
                position: static;
                margin-top: 10px;
                width: 100%;
            }

            /* 响应式调整语音输入按钮 */
            .voice-input-container {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
	<!-- 摄像头小窗口 -->
	<div class="camera-container">
	    <video id="video" autoplay></video>
	    <div class="camera-timer">
	        下次拍摄: <span id="countdown">10</span>秒
	    </div>
	</div>
    <div class="container">
        <div class="header">
            <h1>智能考试系统</h1>
            <p>大数据分析专业考试</p>
            <!-- 新增：退出考试按钮 -->
            <button class="exit-exam-btn" id="exit-exam-btn">
                <i class="fas fa-sign-out-alt"></i> 退出考试
            </button>
            <div class="progress-info">
                <span id="progress-text">0/0</span>
            </div>
            <div class="progress-bar">
                <div class="progress" id="progress-fill"></div>
            </div>
        </div>
        
        <div class="question-container">
            <div class="question-header">
                <h2>题目内容</h2>
                <div class="question-number">第 <span id="question-num">0</span> 题</div>
            </div>
            <div class="question-content" id="question-content">
                欢迎使用智能考试系统！点击下方按钮开始考试。
            </div>
        </div>
        
        <div class="answer-container" id="answer-container" style="display:none;">
            <h3><i class="fas fa-edit"></i> 您的答案</h3>
            <textarea id="answer-input" placeholder="请在此输入您的答案..."></textarea>
            
            <!-- 新增语音输入区域 -->
            <div class="voice-input-container">
                <button class="voice-btn voice-btn-start" id="start-recording-btn">
                    <i class="fas fa-microphone"></i> 开始录音
                </button>
                <button class="voice-btn voice-btn-stop" id="stop-recording-btn" disabled>
                    <i class="fas fa-stop"></i> 停止录音
                </button>
                <div class="voice-status">
                    <div class="recording-indicator" id="recording-indicator"></div>
                    <span id="recording-status">准备就绪</span>
                </div>
            </div>
        </div>
        
        <div class="btn-container">
            <button class="btn btn-warning" id="human-intervene-btn" style="display:none;">
                <i class="fas fa-hands-helping"></i> 申请人工介入
            </button>
            <button class="btn btn-primary" id="submit-btn" style="display:none;">
                <i class="fas fa-paper-plane"></i> 提交答案
            </button>
            <button class="btn btn-primary" id="start-btn">
                <i class="fas fa-play"></i> 开始考试
            </button>
        </div>
        
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在处理中，请稍候...</p>
        </div>
        
        <div class="result-container" id="result-container">
            <div class="result-header">
                <h3><i class="fas fa-chart-line"></i> 评分结果</h3>
                <div class="score"><span id="score-value">0</span>/10</div>
            </div>
            <div class="feedback">
                <h4><i class="fas fa-comment-alt"></i> 详细反馈</h4>
                <div id="feedback-content">
                    等待评分结果...
                </div>
            </div>
            
            <div class="next-btn-container">
                <button class="btn next-btn" id="next-btn" style="display:none;">
                    <i class="fas fa-arrow-right"></i> 下一题
                </button>
            </div>
        </div>
        
        <div class="total-score-container" id="total-score-container">
            <div class="total-score-header">
                <h3><i class="fas fa-trophy"></i> 考试总分</h3>
                <div class="total-score"><span id="total-score-value">0</span>/<span id="max-score-value">50</span></div>
            </div>
            
            <div class="question-scores" id="question-scores">
                <h4><i class="fas fa-list-ol"></i> 每题得分</h4>
                <div id="scores-list"></div>
            </div>
        </div>
    </div>

    <script>
        // 后端API基础URL
        const API_BASE_URL = 'http://127.0.0.1:5000';
        
        document.addEventListener('DOMContentLoaded', function() {
            const startBtn = document.getElementById('start-btn');
            const submitBtn = document.getElementById('submit-btn');
            const nextBtn = document.getElementById('next-btn');
            const resultContainer = document.getElementById('result-container');
            const answerContainer = document.getElementById('answer-container');
            const humanInterveneBtn = document.getElementById('human-intervene-btn');
            const questionNum = document.getElementById('question-num');
            const progressText = document.getElementById('progress-text');
            const progressFill = document.getElementById('progress-fill');
            const questionContent = document.getElementById('question-content');
            const loading = document.getElementById('loading');
            const scoreValue = document.getElementById('score-value');
            const feedbackContent = document.getElementById('feedback-content');
            const totalScoreContainer = document.getElementById('total-score-container');
            const totalScoreValue = document.getElementById('total-score-value');
            const maxScoreValue = document.getElementById('max-score-value');
            const scoresList = document.getElementById('scores-list');
            const exitExamBtn = document.getElementById('exit-exam-btn');
            
            // 新增语音输入相关元素
            const startRecordingBtn = document.getElementById('start-recording-btn');
            const stopRecordingBtn = document.getElementById('stop-recording-btn');
            const recordingIndicator = document.getElementById('recording-indicator');
            const recordingStatus = document.getElementById('recording-status');
            const answerInput = document.getElementById('answer-input');
            
			// 摄像头相关元素
			const video = document.getElementById('video');
			const countdownEl = document.getElementById('countdown');
			
            let currentQuestion = 0;
            let maxQuestions = 0;
            let recognition = null;
            let isRecording = false;
			let stream = null;
			let captureInterval = null;
			let countdown = 10;
			let image_from_database = null;
            function loadUserInfo() {
                const username = sessionStorage.getItem('username');
                // console.log(username)
                // 未登录则跳转回登录页
                if (!username) {
                    window.location.href = 'login.html';
                    return;
                }else{
                    const name = {"Name":username}
                    const jsonData = JSON.stringify(name)
                    fetch("http://127.0.0.1:5003/imagebase",{
                        method:"POST",
                        headers:{
                            "Content-Type":"application/json"
                        },
                        body:jsonData,
                    })
                    .then(response=>response.json())
                    .then(data=>{
                        // console.log(data.Image)
                        image_from_database=data.Image
                    })
                }
                
            }
			// 初始化摄像头
			async function startCamera() {
			    try {
			        stream = await navigator.mediaDevices.getUserMedia({ video: true });
			        video.srcObject = stream;
			        
			        // 开始倒计时和自动拍照
			        startCountdown();
			        
			        console.log('摄像头已启动，将每10秒自动拍摄一次');
			    } catch (error) {
			        console.error('访问摄像头时出错:', error);
			        alert('无法访问摄像头，请确保您已授予权限');
			    }
			}
			
			// 开始倒计时
			function startCountdown() {
			    // 先拍一张
			    captureImage();
			    
			    // 重置倒计时
			    countdown = 10;
			    countdownEl.textContent = countdown;
			    
			    // 设置间隔
			    captureInterval = setInterval(() => {
			        countdown--;
			        countdownEl.textContent = countdown;
			        
			        if (countdown <= 0) {
			            captureImage();
			            countdown = 10;
			        }
			    }, 1000);
			}
			
			// 拍照
			function captureImage() {
			    const canvas = document.createElement('canvas');
			    canvas.width = video.videoWidth;
			    canvas.height = video.videoHeight;
			    const ctx = canvas.getContext('2d');
			    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
			    
			    // 添加闪烁效果
			    video.classList.add('camera-flash');
			    setTimeout(() => {
			        video.classList.remove('camera-flash');
			    }, 500);
			    
			    // 转换为Base64
			    const capturedImage = canvas.toDataURL('image/jpeg');
			    const base64Data = capturedImage.split(',')[1]; 
			    // console.log(base64Data)
			    // 发送到人脸识别API
				
				fetch('http://127.0.0.1:5006/face', {
				    method: "POST",
				    headers: {
				        "Content-Type": "application/json"
				    },
				    body: JSON.stringify({data: base64Data}),
				})
				.then(response => response.json())
				.then(data => {
					console.log(data)
				    if(data.error_code != 0) {
				        alert("请不要离开屏幕");
				    } else {
				        // 检查头部角度
				        if (-20 > data.result.face_list[0].angle.yaw || data.result.face_list[0].angle.yaw > 20) {
				            alert("请面向屏幕");
				        }
				        if(-20 > data.result.face_list[0].angle.pitch || data.result.face_list[0].angle.pitch > 20) {
				            alert("请面向屏幕");
				        }
						const imageBase = {"image1": image_from_database, "image2": base64Data};
						const imageJson = JSON.stringify(imageBase);
						fetch('http://127.0.0.1:5003/image', {
						    method: "POST",
						    headers: {
						        "Content-Type": "application/json"
						    },
						    body: JSON.stringify({data: imageJson}),
						    })
						    .then(response => response.json())
						    .then(data => {
						        console.log("人脸匹配分数: " + data.result.score);
								if(data.result.score<80){
									alert("请本人考试")
								}else{
						
								}
						    });
						
				    }
				});
				
			}
            // 初始化语音识别
            function initSpeechRecognition() {
                try {
                    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
                    if (!SpeechRecognition) {
                        console.error('浏览器不支持语音识别API');
                        startRecordingBtn.disabled = true;
                        recordingStatus.textContent = '浏览器不支持语音识别';
                        return false;
                    }
                    
                    recognition = new SpeechRecognition();
                    recognition.continuous = true;
                    recognition.interimResults = true;
                    recognition.lang = 'zh-CN';
                    
                    recognition.onstart = function() {
                        isRecording = true;
                        startRecordingBtn.disabled = true;
                        stopRecordingBtn.disabled = false;
                        recordingIndicator.style.display = 'block';
                        recordingStatus.textContent = '正在录音...';
                    };
                    
                    recognition.onerror = function(event) {
                        console.error('语音识别错误:', event.error);
                        stopRecording();
                        recordingStatus.textContent = `识别错误: ${event.error}`;
                    };
                    
                    recognition.onend = function() {
                        if (isRecording) {
                            // 如果仍在录音状态但识别结束，则重新启动
                            recognition.start();
                        }
                    };
                    
                    recognition.onresult = function(event) {
                        let interimTranscript = '';
                        let finalTranscript = '';
                        
                        for (let i = event.resultIndex; i < event.results.length; i++) {
                            const transcript = event.results[i][0].transcript;
                            if (event.results[i].isFinal) {
                                finalTranscript += transcript;
                            } else {
                                interimTranscript += transcript;
                            }
                        }
                        
                        // 更新文本框内容
                        const currentText = answerInput.value;
                        answerInput.value = currentText + finalTranscript;
                        
                        // 如果是临时结果，可以显示在状态中
                        if (interimTranscript) {
                            recordingStatus.textContent = `识别中: ${interimTranscript}`;
                        } else if (finalTranscript) {
                            recordingStatus.textContent = '正在录音...';
                        }
                    };
                    
                    return true;
                } catch (error) {
                    console.error('语音识别初始化失败:', error);
                    recordingStatus.textContent = '语音识别初始化失败';
                    return false;
                }
            }
            
            // 开始录音
            function startRecording() {
                if (!recognition) {
                    if (!initSpeechRecognition()) {
                        return;
                    }
                }
                
                try {
                    recognition.start();
                } catch (error) {
                    console.error('录音启动失败:', error);
                    recordingStatus.textContent = '录音启动失败';
                }
            }
            
            // 停止录音
            function stopRecording() {
                if (recognition) {
                    isRecording = false;
                    recognition.stop();
                    startRecordingBtn.disabled = false;
                    stopRecordingBtn.disabled = true;
                    recordingIndicator.style.display = 'none';
                    recordingStatus.textContent = '准备就绪';
                }
            }
            
            // 绑定语音按钮事件
            startRecordingBtn.addEventListener('click', startRecording);
            stopRecordingBtn.addEventListener('click', stopRecording);
            
            // 更新进度
            function updateProgress() {
                questionNum.textContent = currentQuestion;
                progressText.textContent = `${currentQuestion}/${maxQuestions}`;
                progressFill.style.width = `${(currentQuestion / maxQuestions) * 100}%`;
            }
            
            // 显示加载状态
            function showLoading() {
                loading.style.display = 'block';
            }
            
            // 隐藏加载状态
            function hideLoading() {
                loading.style.display = 'none';
            }
            
            // 处理API请求错误
            function handleApiError(error) {
                console.error('API请求错误:', error);
                hideLoading();
                alert(`请求失败: ${error.message || '未知错误'}`);
            }
            
            // 新增：退出考试按钮点击事件
            exitExamBtn.addEventListener('click', function() {
                if (confirm('确定要退出考试吗？未完成的题目将不会保存。')) {
                    window.location.href = 'student_home.html';
                }
            });
            
            // 开始考试
            startBtn.addEventListener('click', function() {
                showLoading();
                
                fetch(`${API_BASE_URL}/start_exam`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'include'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.error || `HTTP错误! 状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    questionContent.textContent = data.question;
                    currentQuestion = data.question_count;
                    maxQuestions = data.max_questions;
                    updateProgress();
                    
                    // 显示答题区域
                    answerContainer.style.display = 'block';
                    submitBtn.style.display = 'block';
                    humanInterveneBtn.style.display = 'block';
                    startBtn.style.display = 'none';
                    resultContainer.style.display = 'none';
                    totalScoreContainer.style.display = 'none';
                    
                    // 滚动到题目区域
                    document.querySelector('.question-container').scrollIntoView({ behavior: 'smooth' });
                })
                .catch(handleApiError);
            });
            
            // 提交答案
            submitBtn.addEventListener('click', function() {
                const answer = answerInput.value.trim();
                
                if (!answer) {
                    alert('请输入答案后再提交');
                    return;
                }
                
                showLoading();
                
                fetch(`${API_BASE_URL}/submit_answer`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({ answer: answer })
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.error || `HTTP错误! 状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    // 显示评分结果
                    scoreValue.textContent = data.score.toFixed(1);
                    feedbackContent.textContent = data.feedback;
                    resultContainer.style.display = 'block';
                    
                    // 更新进度
                    currentQuestion = data.question_count;
                    updateProgress();
                    
                    // 处理追问情况
                    if (data.need_follow_up && data.follow_up_question) {
                        questionContent.textContent = data.follow_up_question;
                        answerInput.value = '';
                        nextBtn.style.display = 'none';
                    } else {
                        nextBtn.style.display = 'block';
                    }
                    
                    // 滚动到结果区域
                    resultContainer.scrollIntoView({ behavior: 'smooth' });
                })
                .catch(handleApiError)
                .finally(() => {
                    hideLoading();
                });
            });
            
            // 下一题
            nextBtn.addEventListener('click', function() {
                showLoading();
                
                fetch(`${API_BASE_URL}/next_question`, {
                    method: 'GET',
                    headers: {
                        'Accept': 'application/json'
                    },
                    credentials: 'include'
                })
                .then(response => {
                    if (!response.ok) {
                        return response.json().then(errData => {
                            throw new Error(errData.error || `HTTP错误! 状态码: ${response.status}`);
                        });
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    if (data.message) {
                        // 显示总分
                        totalScoreValue.textContent = data.total_score.toFixed(1);
                        maxScoreValue.textContent = data.max_possible_score;
                        totalScoreContainer.style.display = 'block';
                        
                        // 显示每题得分
                        scoresList.innerHTML = '';
                        data.question_scores.forEach((score, index) => {
                            const scoreItem = document.createElement('div');
                            scoreItem.className = 'score-item';
                            scoreItem.innerHTML = `
                                <span>第 ${index + 1} 题得分:</span>
                                <span>${score.toFixed(1)}/10</span>
                            `;
                            scoresList.appendChild(scoreItem);
                        });
                        
                        // 滚动到总分区域
                        totalScoreContainer.scrollIntoView({ behavior: 'smooth' });
                        
                        // 隐藏结果容器和下一题按钮
                        resultContainer.style.display = 'none';
                        nextBtn.style.display = 'none';
                    } else {
                        // 更新题目
                        questionContent.textContent = data.question;
                        answerInput.value = '';
                        resultContainer.style.display = 'none';
                        nextBtn.style.display = 'none';
                        
                        // 更新进度
                        currentQuestion = data.question_count;
                        updateProgress();
                        
                        // 滚动到题目区域
                        document.querySelector('.question-container').scrollIntoView({ behavior: 'smooth' });
                        
                        // 焦点定位到答案输入框
                        answerInput.focus();
                    }
                })
                .catch(handleApiError);
            });
            
            // 申请人工介入
            humanInterveneBtn.addEventListener('click', function() {
                showLoading();
                
                fetch(`${API_BASE_URL}/request_human_intervention`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({})
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP错误! 状态码: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.error) {
                        throw new Error(data.error);
                    }
                    
                    alert(data.message);
                    console.log('人工介入上下文:', data.context);
                })
                .catch(handleApiError);
            });
            
            // 页面卸载时停止录音
            window.addEventListener('beforeunload', function() {
                if (isRecording) {
                    stopRecording();
                }
            });
			// 启动摄像头
			startCamera();
			loadUserInfo()
        });
    </script>
</body>
</html>